package com.qidian.by.util.pojo;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONReader;
import com.qidian.by.util.exceptions.ServiceExceptionEnum;

import java.io.Serializable;
import java.lang.reflect.Type;
import java.util.List;

/**
 * @Author: CoolPro
 * @Description:
 * @Time: 2024-05-06 18:40
 **/

public class EsResult<T> implements Serializable {
    private String msg;
    private Integer code;
    private T data;
    ServiceExceptionEnum exception;
    public EsResult() {
    }

    public EsResult(String msg, Integer code, T data) {
        this.msg = msg;
        this.code = code;
        this.data = data;
    }

    public EsResult(ServiceExceptionEnum exception) {
        this.exception = exception;
        this.code = exception.getCode();
        this.msg = exception.getMessage();
    }

    public static EsResult ok(String msg, Object data) {
        return new EsResult(msg, 200, data);
    }
    public static EsResult ok() {
        return new EsResult("操作成功", 200, null);
    }
    public static EsResult ok(Object data) {
        return new EsResult("操作成功", 200, data);
    }
//    error
    public static EsResult error(ServiceExceptionEnum exception) {
        return new EsResult(exception);
    }
    public static EsResult error() {
        return new EsResult(ServiceExceptionEnum.VERIFICATION_TOKEN_ERROR);
    }

    public static EsResult isSuccess(int result) {
        return result == 1? EsResult.ok() : EsResult.error(ServiceExceptionEnum.DEFAULT_FAIL);
    }
    public static String object2json(Object obj){
        return JSON.toJSONString(obj);
    }

    public static <T> T json2object(String searchItem,Class<T> clazz) {
        return JSON.parseObject(searchItem,clazz);
    }

    public static <T> List<T> json2list(String cartJson, Class<T> clazz) {
        return JSON.parseArray(cartJson,clazz);
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public Integer getCode() {
        return code;
    }

    public ServiceExceptionEnum getException() {
        return exception;
    }

    public void setException(ServiceExceptionEnum exception) {
        this.exception = exception;
    }

    public void setCode(Integer code) {
        this.code = code;
    }

    public T getData() {
        return data;
    }

    public void setData(T data) {
        this.data = data;
    }
}
